# -*- coding: utf-8 -*-


"""
Game loading screen.

Button "Load" -> screen "Players order".

Need:
    - Nothing
Changes:
    - All gamestate
"""

import urllib2
import socket

from kivy.app import App
from kivy.logger import Logger
from kivy.properties import StringProperty
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

from model.gamestate import *
from ui.hat_widget import HatWidget, open_ok_popup
from model.json_loader import JsonLoader
import constants


class LoadGameScreen(HatWidget):
    game_id = StringProperty()
    pin_code = StringProperty()
    """ Drawing screen which will be used for loading a game
    """

    def __init__(self, game_state, presenter, **kwargs):
        self.HOST = presenter.settings.game.server_name
        self.game_state = game_state
        self.presenter = presenter
        super(LoadGameScreen, self).__init__(**kwargs)
        self.game_id = u''
        self.pin_code = u''
        self.input_id.focus = True
        self.load_button.enabled = False
        self.is_correct_id = False
        self.is_correct_pin = False

    #def update_id(self, value):
        #self.game_id = value

        #if self.game_id.isdigit() and self.pin_code.isdigit():
            #self.load_button.enabled = True
        #else:
            #self.load_button.enabled = False

    #def update_pin(self, value):
        #self.pin_code = value

        #if self.game_id.isdigit() and self.pin_code.isdigit():
            #self.load_button.enabled = True
        #else:
            #self.load_button.enabled = False

    def on_load_pressed(self):
        """ Called when button "Load" is pressed". Load gamestate by id.

            loads json with gamestate from
            <HOST>/game_template_json?game_id=<game_id>&pin=<pin_code>
            changes phase to PLAYERS_ORDER
        """
        loader = JsonLoader()
        try:
            Logger.debug('on_load_pressed(): sending request: game_id: ' +
                         str(self.input_id.text) + ' , pin: ' +
                         str(self.input_pin.text))
            self.presenter.game_state = loader.load_game_from_url(
                self.HOST + '/game_template_json?game_id=' +
                self.input_id.text +
                '&pin=' + self.input_pin.text)
            self.game_state.remote_id = self.game_id
            self.game_state.pin_code = self.pin_code
        except urllib2.HTTPError as msg:
            if msg.code == 404:
                error_text = _('Game not found.\nCheck you game-id')
            elif msg.code == 403:
                error_text = _('Incorrect PIN number')
            elif msg.code == 424:
                error_text = _('Specified game cannot be loaded')
            else:
                error_text = _('Network error')
            open_ok_popup(_('Error'), error_text, self)
            return
        except urllib2.URLError as msg:
            Logger.debug('on_load_pressed(): URLError: %s' % msg.reason)
            open_ok_popup(_('Error'), _('Network error'), self)
            return
        except urllib2.socket.timeout:
            open_ok_popup(_('Error'), _('Network error'), self)
            return
        except:
            open_ok_popup(_('Error'), _('Unknown error'), self)
            return

        self.presenter.change_phase(Phase.PLAYERS_ORDER)

    def go_back(self):
        self.presenter.change_phase(Phase.WELCOME)

    def check_id(self):
        self.is_correct_id = self.input_id.text.isdigit()
        self.load_button.enabled = (self.is_correct_id and
                                    self.is_correct_pin)

    def check_pin(self):
        self.is_correct_pin =\
            (self.input_pin.text.isdigit() and
             len(self.input_pin.text) <= constants.MAX_PIN_LENGTH
             and len(self.input_pin.text) >= constants.MIN_PIN_LENGTH)
        self.load_button.enabled = (self.is_correct_id and self.is_correct_pin)

    def try_go_next(self):
        if self.load_button.enabled:
            self.on_load_pressed()
